/*
* Best PlaceEdit
* 用于编辑控件实时点击进入编辑状态,基于dwr和prototype库
* 主入口：new Best.PlaceEdit
* 参数：element：被编辑内容父结点id
*	   resourceId: 被编辑内容所要存储数据库的对象id
*	   saveFunc: 用于存储数据的函数，由用户提供该函数，该函数应该内部以使用dwr函数为主。
*			saveFunc(resouceId, data, callback);
*			PlaceEdit以该形式调用saveFunc函数，不涉及其他的后台存储细节。用户应在该
*			在该函数内实现ajax的函数调用，并注册PlaceEdit所传入的callback函数
* 可选参数：
* 	saveText: 保存按钮的显示名字
*	cancelText: 取消按钮的显示名字
*	savaButStyle: 保存按钮的显示风格,
*	cancelButStyle: 取消按钮的显示风格,
*	orText: 两个按钮间的连接字串
*	savingText: 保存状态中的显示字串
*	clickToEditText: 编辑提示字串
*	emptyText: 空档编辑提示字串
*	editType: 编辑框类型 提供input和textarea两类编辑框
*   maxLength: 编辑框最大限制输入字数
*   btnBelow: 按钮是否显示在输入框下面还是右边
*	editStyle: 编辑框style,
*	highLightColor: 高亮显示背景色,
*	dataStream: 被编辑内容所属的数据,
*	itemIdx: 该数据对象中的项
*	afterFinishedFunc: 编辑结束后的回调函数
*	param: 编辑结束后的回调函数的参数,
*	dofirst: 前期准备函数   
*   space: 用户指定的空位占位元素，用于对抗overflow情况下不能指定元素的height问题
* 	userCallBack: 用户自行注册回调函数, 将回传{success, value}做为参数 用于辨明调用是否成功以及修改后值
* 
* 需要Browser.js支持
*/
if (Best==undefined){
	var Best={};
}
Best.PlaceEdit = Class.create();
Best.PlaceEdit.prototype = {
	initialize: function(element, resourceId, saveFunc) {
		element = $(element);
		this.element = element;
		//this.text = this._getInputCharsFromDisplayHTML(element.innerHTML);
		this.resourceId = resourceId;
		this.options = Object.extend({
			isEditOnClick: false,  //是否点击之后进入编辑状态
			saveText: '保　存',
			cancelText: '取　消',
			savaButStyle: 'Butt',
			cancelButStyle: 'CancelButt',			
			orText: '&nbsp;',
			savingText: '<i>保存中...</i>&nbsp;',
			clickToEditText: '点击并编辑',
			emptyText: '',
			loadingText: 'Loading...',
			editType: 'input',
			textrows: 4,
			maxLength: 1000,
			btnBelow: true,
			editStyle: 'inputEdit',
			highLightColor: '#FFFFE1',
			dataStream: null,
			itemIdx:null,
			afterFinishedFunc: Prototype.emptyFunction,
			param: false,
			dofirst: Prototype.emptyFunction,
			canBeNull: true,
			space: false,
			spaceHeight: '16px',
			userCallBack: Prototype.emptyFunction,
			editIcon: null,
			editIconElem: null,
			attchEventToParent : false,
			bExtendText: false, // 是否需要对较短的输入，如空格，在显示成html文本的时候增加显示长度，方便找到输入处，应用在博客名称和描述等地方
			extendText: '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
		}, arguments[3] || {} );
	
		this._convertForSpaceAndEmpty();
		
		if (this.options.maxLength <= 0) {
			if (this.options.editType == 'input')
				this.options.maxLength = 30;
			else
				this.options.maxLength = 200;
		}
		this.saveFunc = saveFunc;
		this.eventReg();
	},
	
	resetAll: function(){
		window.should_I_ignore_stuff_because_is_editing = 0;
		window.should_I_ignore_stuff_because_of_button_action = 0;
	},
	
	_getInput: function() {
		var	editString = '';
		if (this.options.editType == 'input')		
			editString = '<input type="text" id="content' + this.element.id + '" class="' + this.options.editStyle + ' input_textbox" style="padding:2px;" maxlength="' + this.options.maxLength + '"/>';
		else 
			editString = '<textarea id="content'+ this.element.id + '" class="'+ this.options.editStyle + '" style="padding:4px;" maxlength="' + this.options.maxLength + '" cols="20" rows="' + this.options.textrows + '"></textarea>';
		if (this.options.btnBelow)
			editString += '<br/>';
		else
			editString += '&nbsp;';
		editString += '<input type="button" class="' + this.options.savaButStyle + ' input_button" value="' + this.options.saveText + '" id="submit' + this.element.id + '"/>'+
			this.options.orText + '<input type="button" '+ 'class="' + this.options.cancelButStyle + ' input_button" value="' + this.options.cancelText + '" id="reset'+this.element.id + '"/>';		
		return editString;
	},
	
	startEditing: function(){
		if(window.should_I_ignore_stuff_because_is_editing||window.should_I_ignore_stuff_because_of_button_action)
			return;
		window.should_I_ignore_stuff_because_is_editing=1;
		
		this.options.dofirst();
		
		this.isEditing = true;
		this.unhighLight();
		// 获取现有编辑况中的内容
		this.text = this._getInputCharsFromDisplayHTML(this.element.innerHTML);
		// 使用占位符的情况下
		if ((this.options.space) && (this.text==this.options.space))
			this.text='';
		// 使用用户输入提示的情况下		
		else if (this.text == this.options.emptyText) 
			this.text='';
		// 产生出编辑框并显示
		this.element.innerHTML = this._getInput();
		var	content = $('content'+this.element.id);
		content.value = Utils.TrimSBCandDBC(this.text);
		content.focus();
		content.select();
		$('submit'+this.element.id).onclick = this.savingChanges.bind(this);
		$('reset'+this.element.id).onclick = this.endEditing.bind(this);
	},
	
	savingChanges: function() {
		var editValue = '';
		// 获取用户输入值
		if (this.options.editType == 'input')
			editValue = $('content'+this.element.id).value;
		else
			editValue = $('content'+this.element.id).value;
			
		if (Utils.TrimSBCandDBC(editValue) == '' && editValue != '') {
			editValue = ' ';
		}
						
		//没有对内容做编辑
		if (editValue == this.text){
			this.editValue = this.text;
			this.endEditing();
			return;
		}
		else{
			if ((!this.options.canBeNull) && (editValue=='')){
				this.endEditing();
				return;
			}
			
			this.editValue = editValue;
			// 显示保持提示字串
			this.element.innerHTML = this.options.savingText;
			
			// 保存到后台数据库中	
			if (this.saveFunc){
				var saveString = editValue.replace(/\r/g, '');
				if (saveString.length > this.options.maxLength){
					alert('输入的内容过长，请不要超过'+this.options.maxLength+'个字');
					return false;
				}
				this.saveFunc(this.resourceId, saveString, this.callBackFunc.bind(this));
			}
			else {
				this.callBackFunc(true);
				return;
			}
		}
	},
	
	callBackFunc: function(success){
		if (success){
			// 如果用户输入为空
			if (this.editValue=='')
				this._handleForEmptyInput();
			else {
				// 显示用户输入的内容
				var chars = this._getDisplayHTMLFromInputChars(this.editValue);
				
				if (this.options.bExtendText) {
					if (chars == '&nbsp;')
						chars = this.options.extendText;
				}
				
				this.element.innerHTML = chars;
			}
			
			// 更新数据缓存
			if (typeof this.options.dataStream == Array){
				var value = this.editValue;
				if (this.options.itemIdx){
					var item = this.options.itemIdx;
					this.options.dataStream.each(function(e){e[item]=value});
				}
				else
					this.options.dataStream.each(function(e){e=value});
			}
			else if (this.options.dataStream){
				if (this.options.itemIdx)
					this.options.dataStream[this.options.itemIdx] = this.editValue;
				else
					this.options.dataStream = this.editValue;
			}
		}
		else{
			if (this.text == '')
				this._handleForEmptyInput();
			else
				this.element.innerHTML = this.text;
		}
		window.should_I_ignore_stuff_because_is_editing= 0;
		this.isEditing = false;		
	
		this.options.afterFinishedFunc(this.options.param);
		this.options.userCallBack({success:success, value:this.editValue});
	},
		
	endEditing: function(){
		window.should_I_ignore_stuff_because_is_editing= 0;
		this.isEditing = false;
		if (this.text=='')
			this._handleForEmptyInput();
		else
			this.element.innerHTML = this._getDisplayHTMLFromInputChars(this.text);	
		this.options.afterFinishedFunc(this.options.param);
		this.options.userCallBack({success:false, value:this.editValue});
	},
	
	onMouseover: function(){
		if(window.should_I_ignore_stuff_because_is_editing||window.should_I_ignore_stuff_because_of_button_action)
			return;
		this.highLight();
	},
	
	onMouseout: function(){
//		if(this.hideTimer)
//			clearTimeout(this.hideTimer);
//		var	bindUnhighLight = this.unhighLight.bind(this);
//		this.hideTimer=setTimeout(bindUnhighLight ,1000);
		this.unhighLight();
	},
	
	highLight: function(){
//		if(this.hideTimer)
//			clearTimeout(this.hideTimer);
		if (!$(this.options.editIcon)) {
			this.element.style.backgroundColor = this.options.highLightColor;
		} else {
//			var pos = Position.cumulativeOffset($(this.options.editIcon));
//			this.options.editIconElem.style.left = pos[0] + 'px';
//			this.options.editIconElem.style.top = pos[1] + 'px';
			//this.options.editIconElem.style.display = '';
			$(this.options.editIcon).style.display = '';
		}
	
	},
			
	unhighLight: function(){
//		if(this.hideTimer)
//			clearTimeout(this.hideTimer);
		if (!$(this.options.editIcon)) {
			this.element.style.backgroundColor="";
		} else {
			//this.options.editIconElem.style.display = 'none';
			$(this.options.editIcon).style.display = 'none';
		}
	},
	
	eventReg: function(){
		if(this.options.isEditOnClick){
			this.element.onclick = this.startEditing.bind(this);
			this.element.onmouseover = this.onMouseover.bind(this);
			this.element.onmouseout = this.onMouseout.bind(this);
		}		
		if ($(this.options.editIcon)) {
			$(this.options.editIcon).style.position = 'absolute';
			$(this.options.editIcon).innerHTML = '&nbsp;<span class="c05" style="cursor:pointer;font:normal 14px \'宋体\';">[编辑]</span>';
			$(this.options.editIcon).style.width = '80px';
			$(this.options.editIcon).style.display = 'none';
			var node = $(this.options.editIcon);
			if (this.options.attchEventToParent) {
				node = this.element.parentNode;
			}
			node.onclick = this.startEditing.bind(this);
			node.onmouseover = this.onMouseover.bind(this);
			node.onmouseout = this.onMouseout.bind(this);
		}
	},
	
	_getInputCharsFromDisplayHTML: function(sHTML){
		var chars = sHTML;
		chars = chars.replace(/<br>/ig, (Browser.isFirefox() ? "\n" : "\r\n"));
		chars = chars.replace(/&lt;/g, "<");
		chars = chars.replace(/&gt;/g, ">");
		chars = chars.replace(/&quot;/g, "\"");
		chars = chars.replace(/&#039;/g, "'");
		chars = chars.replace(/&amp;/g, "&");
		chars = chars.replace(/&nbsp;/g, " ");
		return chars;
	},
	
	_getDisplayHTMLFromInputChars: function(sChars){
		var html = sChars;
		html = html.replace(/&/g, "&amp;");
		html = html.replace(/</g, "&lt;");
		html = html.replace(/>/g, "&gt;");
		html = html.replace(/"/g, "&quot;");
		html = html.replace(/'/g, "&#039;");
		html = html.replace(/ /g, "&nbsp;");
		html = html.replace((Browser.isFirefox() ? /\n/g : /\r\n/g), "<br>");		
		return html;
	},
	
	// 处理输入为空时显示内容
	_handleForEmptyInput: function(){
		// 如果使用占位符则填充该占位符
		// 否则使用用户空输入提示
		if (this.options.space)
			this.element.innerHTML = this.options.space;
		else
			this.element.innerHTML = this.options.emptyText;
	},
	
	_convertForSpaceAndEmpty: function(){
		var tempNode = $('__$$__temp__$$__');
		if (tempNode==null){
				tempNode = document.createElement('div');
				tempNode.style.display = 'none';
				document.body.appendChild(tempNode);
				tempNode.id = '__$$__temp__$$__';
		}
		if (this.options.space){
			tempNode.innerHTML = this.options.space;
			this.options.space = tempNode.innerHTML;
		}
		if (this.options.emptyText){
			tempNode.innerHTML = this.options.emptyText;
			this.options.emptyText = tempNode.innerHTML;		
		}
	}
};

